import { createStore } from 'vuex'
import { RootState } from './types'
import login from './modules/login'
import dashboard from './modules/dashboard'
import icafe from './modules/customer/icafe'
import staff from './modules/company/staff'
import role from './modules/company/role'
import menu from './modules/system/menu'

import { fetchProfile } from '@/api/main/index'
import { getDataList as fetchRegionList } from '@/api/system/region'
import { menusToNavMenus, menusToPermissions } from '@/utils/map-menus'

export default createStore<RootState>({
  state: {
    userInfo: {},
    userMenus: [],
    regions: [],
    defaultAvatar: require('@/assets/img/avatar.png')
  },
  getters: {
    userName(state) {
      return state.userInfo.name
    },
    userAvatar(state) {
      return state.userInfo.avatar !== '' ? state.userInfo.avatar : state.defaultAvatar
    },
    userMenus(state) {
      return state.userMenus
    },
    userNavMenus(state) {
      return menusToNavMenus(state.userMenus)
    },
    userPermissions(state) {
      return menusToPermissions(state.userMenus)
    },
    regions(state) {
      return JSON.parse(JSON.stringify(state.regions).replace(/name/g, 'label').replace(/id/g, 'value'))
    },
    showRegions(state) {
      return (districtId: number) => {
        const regionNames: any[] = []

        _filterRegions(state.regions)

        function _filterRegions(data: any[]): boolean {
          const region: any = data.find((item) => {
            if (item.children && item.children.length) {
              return _filterRegions(item.children)
            }

            return item.id === districtId
          })

          if (region) {
            regionNames.push(region.name)
          }

          return region !== undefined
        }

        return regionNames.reverse().join(' / ')
      }
    }
  },
  mutations: {
    changeUserInfo(state, payload) {
      state.userInfo = payload
    },
    changeUserMenus(state, payload) {
      state.userMenus = payload
    },
    changeRegions(state, payload) {
      state.regions = payload
    }
  },
  actions: {
    async init({ commit }) {
      // 请求用户数据和菜单数据
      const { userInfo, userMenus } = (await fetchProfile())?.data
      commit('changeUserInfo', userInfo)
      commit('changeUserMenus', userMenus)

      // 请求完整行政区域信息
      const regions = (await fetchRegionList())?.data?.list ?? []
      commit('changeRegions', regions)

      return Promise.resolve(true)
    }
  },
  modules: { login, dashboard, icafe, staff, role, menu }
})
